package com.yunxiao.cloud.job.util;

import com.yunxiao.cloud.common.generator.SnowflakeIdWorker;
import com.yunxiao.cloud.job.entity.ScheduleJob;
import com.yunxiao.cloud.job.entity.ScheduleJobLog;
import com.yunxiao.cloud.job.service.ScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @description: TaskJobLog
 * @author: yunxiao
 * @date: 2020/1/13 10:45
 * @version: V1.0
 **/
public class TaskJobLog extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(TaskJobLog.class);


    @Override
    protected void executeInternal(JobExecutionContext context) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1,1);

        ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get(ScheduleJob.JOB_PARAM_KEY);
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtil.getBean("scheduleJobLogService");
        // 定时器日志记录
        ScheduleJobLog logBean = new ScheduleJobLog();

        logBean.setLogId(idWorker.nextId()+"");
        logBean.setJobId(scheduleJob.getJobId());
        logBean.setBeanName(scheduleJob.getBeanName());
        logBean.setParams(scheduleJob.getParams());
        logBean.setCreateTime(new Date());

        long beginTime = System.currentTimeMillis();

        try {
            // 加载并执行定时器的 run 方法
            Object target = SpringContextUtil.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, scheduleJob.getParams());
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus(0);
            logger.info("定时器 === >> "+scheduleJob.getJobId()+"执行成功,耗时 === >> " + executeTime);
        } catch (Exception e) {
            // 异常信息
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int)executeTime);
            logBean.setStatus(1);
            logBean.setError(e.toString());
        } finally {
            scheduleJobLogService.insert(logBean);
        }

    }
}
